package yxy.game.pm2.command.plainsarena;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlainsArenaMessage;
import yxy.game.pm2.module.plainsarena.RankPlainsArena;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.Collection;

/** 中原擂台 中原擂台排行榜 */
@MessageType(proto = Command.PlainsArenaRank, classtype = PlainsArenaMessage.PlainsArenaRankRequest.class)
public class CMD_PlainsArenaRank extends Command<PlainsArenaMessage.PlainsArenaRankRequest> {

	@Override
	public void execute(MessageSource messageSource, PlainsArenaMessage.PlainsArenaRankRequest request) {
		String playerCode = messageSource.getTag();
		int level = request.getLevel();

		PlainsArenaMessage.PlainsArenaRankResponse.Builder response = PlainsArenaMessage.PlainsArenaRankResponse.newBuilder();

		if (level < 1 || level > 5) {
			send(messageSource, response, Result.ParamError);
			return;
		}

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		RankPlainsArena rankPlainsArena = new RankPlainsArena(areaBean.getGroupId(), level);
		try {
			PlayerHandle playerHandle = new PlayerHandle();
			Collection<RankEntry> top = rankPlainsArena.top(rankPlainsArena.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();

				PlainsArenaMessage.PlainsArenaRank.Builder builder = PlainsArenaMessage.PlainsArenaRank.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				response.addRank(builder);
			}
			{
				int playerRank = 0;
				RankEntry entry = rankPlainsArena.get(playerCode);
				if (entry != null) {
					playerRank = rankPlainsArena.rank(playerCode);
				}

				PlainsArenaMessage.PlainsArenaRank.Builder builder = PlainsArenaMessage.PlainsArenaRank.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				response.setMy(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, PlainsArenaMessage.PlainsArenaRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}